package com.breaktian.assemble.http.download;


import com.breaktian.assemble.utils.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by breaktian on 2016/9/2.
 */
public class DownloadUtils {

	private static DownloadUtils instance;

	private final static Object lockObj = new Object();
	private final OkHttpClient mClient;

	private DownLoadListener listener;

	private DownloadUtils() {
		mClient = new OkHttpClient.Builder().connectTimeout(3 * 60, TimeUnit.SECONDS)
				.readTimeout(3 * 60, TimeUnit.SECONDS)
				.addInterceptor(new Interceptor() {
					@Override
					public Response intercept(Chain chain) throws IOException {
						// 拦截
						Response originalResponse = chain.proceed(chain.request());
						// 包装响应体并返回
						return originalResponse.newBuilder()
								.body(new ProgressResponseBody(originalResponse.body(), new ProgressResponseListener() {
											@Override
											public void onResponseProgress(long bytesRead, long contentLength, boolean done) {
												LogUtil.d("onResponseProgress bytesRead:" + bytesRead + " contentLength:" + contentLength + " done:" + done);
												if (DownloadUtils.this.listener != null) {
													DownloadUtils.this.listener.onProgress(bytesRead, contentLength, done);
												}

											}
										}))
								.build();
					}
				}).build();
	}

	public static DownloadUtils get() {
		if (instance == null) {
			synchronized (lockObj) {
				if (instance == null) {
					instance = new DownloadUtils();
				}
			}
		}
		return instance;
	}

	public void downloadFile(String url, final File file, DownLoadListener listener) {
		this.listener = listener;

		Request request = new Request.Builder().url(url).build();

		mClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				e.printStackTrace();
				LogUtil.d("onFailure " + e.getMessage());
				if (DownloadUtils.this.listener != null)
					DownloadUtils.this.listener.onFail(file);

			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				// LogUtil.d("onResponse "+response.body().string());
				InputStream is = null;
				byte[] buf = new byte[2048];
				int len = 0;
				FileOutputStream fos = null;
				try {
					is = response.body().byteStream();
					fos = new FileOutputStream(file);
					while ((len = is.read(buf)) != -1) {
						fos.write(buf, 0, len);
					}
					fos.flush();
					if (DownloadUtils.this.listener != null) {
						DownloadUtils.this.listener.onSucess(file);
						LogUtil.d("文件下载成功");
					}
				} catch (Exception e) {
					e.printStackTrace();
					if (DownloadUtils.this.listener != null) {
						DownloadUtils.this.listener.onFail(file);
						LogUtil.d("文件下载失败");
					}
				} finally {
					try {
						if (is != null)
							is.close();
					} catch (IOException e) {
					}
					try {
						if (fos != null)
							fos.close();
					} catch (IOException e) {
					}
				}

			}
		});

	}

}
